// 引用用户请求api
import auth from '../../api/auth/auth.js';
import user from '../../api/user/user.js';
import friend from '../../api/friend/friend.js';
import usertoGroup from '../../api/usertoGroup/usertoGroup.js';


import {
	setToken,
	setUserInfo,
	getUserInfo
} from '../../utils/auth';


const state = {
	userInfo: getUserInfo() || {
		uNickname: "小A"
	}
}
const mutations = {
	WEBSOCKET_SEND(state, data) {
		state.socketTask.send({
			data,
			async success() {
				console.log('消息发送成功')
			},
		})
	},
	SETUSERINFO(state, data) {
		state.userInfo = data
		setUserInfo(data) //将获取到的token保存到本地
	},
	SETUSERFRIENDNUMBER(state, data) {
		state.userInfo.friendNumber = data.length
		setUserInfo(state.userInfo) //将获取到的token保存到本地
	},
	SETUSERGROUPNUMBER(state, data) {
		state.userInfo.groupNumber = data.length
		setUserInfo(state.userInfo) //将获取到的token保存到本地
	},
}


//下面我是示例的微信小程序的参数，可自行修改请求参数
const actions = {
	/* 获取群组和好友数量 */
	getGroupnumber({
		commit
	}, param) {
		return new Promise((resolve, reject) => {
			usertoGroup.findUserGroupList().then(response => {
				console.log(response, "response");
				commit('SETUSERGROUPNUMBER', response)
				resolve(response)
			}).catch(error => {
				console.log(error)
			})
		})
	},
	getFriendnumber({
		commit
	}, param) {
		return new Promise((resolve, reject) => {
			friend.findFriendList().then(response => {
				console.log(response, "response");
				commit('SETUSERFRIENDNUMBER', response)
				resolve(response)
			}).catch(error => {
				console.log(error)
			})
		})
	},
	wxLogin({
		commit
	}, param) {
		return new Promise((resolve, reject) => {
			auth.wxLogin(param).then(response => {
				// 这里可以自己添加方法
				// 保存获取到的token到本地之类的
				// 必须在resolve之前执行
				setToken(response.access_token) //将获取到的token保存到本地
				resolve(response)
			}).catch(error => {
				if (error.data.code === 400) {
					this.wxLogin()
				}
				console.log(error)
			})
		})
	},
	wxGetUserInfo({
		commit
	}, param) {
		return new Promise((resolve, reject) => {
			user.getUserInfo().then(response => {
				console.log("获取用户消息");
				console.log(response, "response");
				// 这里可以自己添加方法
				// 保存获取到的token到本地之类的
				// 必须在resolve之前执行
				commit('SETUSERINFO', response)
				resolve(response)
			}).catch(error => {
				console.log(error)
			})
		})
	},
	/*  */
	setUserInfoAction({
		commit
	}, param) {
		return new Promise((resolve, reject) => {
			user.changeUserInfo(param).then(response => {
				// 这里可以自己添加方法
				// 保存获取到的token到本地之类的
				// 必须在resolve之前执行
				// commit('SETUSERINFO', response)
				// console.log(response, "response");
				// setUserInfo(response)
				resolve(response)
			}).catch(error => {
				console.log(error)
			})
		})
	}

};


export default {
	namespaced: true,
	state,
	mutations,
	actions
}
